<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\traits\ImageUpload;
use app\model\HistoryImg;
use app\model\ProjectTarget;
use app\model\ReviewCase as ModelCase;
use app\model\Sample as ModelSample;
use app\model\ReviewProject;
use app\model\Community as ModelCommunity;
use app\model\SampleCommunityPivot;
use app\model\SampleProjectTargetPivot;
use app\model\Statistics;
use app\model\UnqualifiedCase;
use Qcloud\Sms\SmsMultiSender;
use think\facade\Config;
use think\facade\Queue;
use think\Request;

class ReviewCase extends BaseController
{

    use ImageUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 8:54
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取案件列表
     */
    public function getReviewCaseList()
    {
        $map = [];
        //社区id
        if ($this->request->has('community_id') && !empty($this->request->param('community_id'))) {
            $community = new ModelCommunity();
            $ids = $community->selectSample($this->request->param('community_id'), $this->request->param('review_project_id'));
            $map[] = ['new_sample_id', 'in', $ids];
        }
        //所属项目id
        if ($this->request->has('review_project_id') && !empty($this->request->param('review_project_id'))) {
            $map[] = ['review_project_id', '=', $this->request->param('review_project_id')];
        }
        //复查状态
        if ($this->request->has('review_status') && !empty($this->request->param('review_status'))) {
            $map[] = ['review_status', '=', $this->request->param('review_status')];
        }
        //审核状态
        if ($this->request->has('audit_status') && !empty($this->request->param('audit_status'))) {
            $map[] = ['audit_status', '=', $this->request->param('audit_status')];
        }
        //审核结果
        if ($this->request->has('audit_result') && !empty($this->request->param('audit_result'))) {
            $map[] = ['audit_result', '=', $this->request->param('audit_result')];
        }
        //样本点
        if ($this->request->has('new_sample_id') && !empty($this->request->param('new_sample_id'))) {
            $map[] = ['new_sample_id', '=', $this->request->param('new_sample_id')];
        }
        $limit = $this->request->param('limit', 0);
        $res = ModelCase::with(['project', 'sample.communities'])->where($map)->order('id desc')->paginate($limit);
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 8:56
     * @return \think\response\Json
     * 获取复查状态
     */
    public function getReviewStatus()
    {
        $res = ModelCase::$review_status;
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 8:57
     * @return \think\response\Json
     * 获取审核状态
     */
    public function getAuditStatus()
    {
        $res = ModelCase::$audit_status;
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 8:57
     * @return \think\response\Json
     * 获取审核结果
     */
    public function getAuditResult()
    {
        $res = ModelCase::$audit_result;
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 9:09
     * @return \think\response\Json
     * 获取搜索项目
     */
    public function getSearchProject()
    {
        $data = ReviewProject::field('id,title')->select()->toArray();
        return $this->response($data);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 9:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据项目id获取对应的样本点
     */
    public function getSearchSample($id)
    {
        $project = ReviewProject::find($id);
        if (is_null($project)) {
            return $this->response(403, '该项目不存在');
        }
        $data = ModelSample::field('id,review_project_id,name')->where(['review_project_id' => $id])->select()->toArray();
        if (empty($data)) {
            return $this->response(403, '该项目不存在样本点');
        }
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 10:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取社区
     */
    public function getSearchCommunity()
    {
        $data = ModelCommunity::field('id,name')->select()->toArray();
        return $this->response($data);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/26
     * @Time: 15:26
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取案件的图片
     */
    public function checkImage($id)
    {
        $res = ModelCase::find($id);

        if (is_null($res)) {
            return $this->response(403, '暂未找到该案件');
        }
        $img_arr = json_decode($res->sync_path, true);
        $url = $res->domain . '' . $img_arr;

        $data = [
            'url' => $url,
            'srcList' => [$url]
        ];
        return $this->response($data);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 15:16
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取案件
     */
    public function getReadCase($id)
    {
        $res = ModelCase::with(['project', 'user', 'unqualified.unadmin', 'sample' => ['communities', 'targets']])->find($id);
        if (is_null($res)) {
            return $this->response(403, '暂未找到此案件');
        }
        //start 同步过来的图片
        $img_arr = json_decode($res->sync_path, true);
        $url = $res->domain . '' . $img_arr;
        if ($res['review_status'] === ModelCase::TWO_REVIEW_STATUS || $res['review_status'] === ModelCase::THREE_REVIEW_STATUS) {
            $review_img = json_decode($res['review_case_path'], true);
            $new_path = [];
            foreach ($review_img as $key => $value) {
                $new_path[] = $value['img_path'] ?? '';
            }
            $res['review_img'] = $review_img;
            $res['new_path'] = $new_path;
        }
        //end 同步
        //start 复查图
//        $img_review_arr = json_decode($res->review_case_path, true);
//        if (is_null($img_review_arr)){
//
//        }else{
//            $url
//        }
        //end 复查图
        $res['syncUrl'] = $url;
        $res['syncImg'] = [$url];
        return $this->response($res->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/30
     * @Time: 10:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 微信端获取案件
     */
    public function getReadCaseWx()
    {
        $id = $this->request->param('id', 0);
        $res = ModelCase::with(['project', 'unqualified.unadmin', 'sample' => ['communities', 'targets']])->find($id);
        if (is_null($res)) {
            return $this->response(403, '暂未找到此案件');
        }
        //start 同步过来的图片
        $img_arr = json_decode($res->sync_path, true);
        $url = $res->domain . '' . $img_arr;

        if ($res['review_status'] === ModelCase::TWO_REVIEW_STATUS || $res['review_status'] === ModelCase::THREE_REVIEW_STATUS) {
            $review_img = json_decode($res['review_case_path'], true);
            $res['review_img'] = $review_img;
        }
        //end 复查图
        $res['syncUrl'] = $url;
        $res['syncImg'] = [$url];
        return $this->response($res->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 17:21
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存审核结果
     */
    public function saveAuditResult()
    {
        $data = $this->request->param();
        $data['audit_status'] = ModelCase::TWO_AUDIT_STATUS;
        $data['audit_people'] = $this->request->uid; //审核人
        $model = ModelCase::find($data['id']);
        if (is_null($model)) {
            return $this->response(403, '暂未找到该案件');
        }
        $un_data = [];
        $img = [];
        if ($data['audit_result'] === ModelCase::TOUR_AUDIT_RESULT) { //不合格案件
            //     $data['review_status'] = ModelCase::THREE_REVIEW_STATUS; //更改状态为不合格
            //新增到不合格记录表
            $un_data = [
                'un_status' => UnqualifiedCase::UNQALIFIED_ONE,
                'audit_status' => UnqualifiedCase::UN_AUDIT_ONE,
            ];
            $img = [
                'case_id'=>$model->id,
                'review_case_path'=>$model['review_case_path']
            ];
        } else if ($data['audit_result'] === ModelCase::THREE_AUDIT_RESULT) { //反弹
            $un_data = [
                'un_status' => UnqualifiedCase::UNQALIFIED_ONE,
                'audit_status' => UnqualifiedCase::UN_AUDIT_TWO,
            ];
            $img = [
                'case_id'=>$model->id,
                'review_case_path'=>$model['review_case_path']
            ];
        } else if ($data['audit_result'] === ModelCase::TWO_AUDIT_RESULT) { // 未整改反弹
            $un_data = [
                'un_status' => UnqualifiedCase::UNQALIFIED_ONE,
                'audit_status' => UnqualifiedCase::UN_AUDIT_THREE,
            ];
            $img = [
                'case_id'=>$model->id,
                'review_case_path'=>$model['review_case_path']
            ];
        }
        $un_data['review_case_id'] = $data['id'] ?? '';
        $un_data['audit_people'] = $this->request->uid ?? '';
        $un_data['un_reason'] = $data['unReason'] ?? '';
        //统计
        Statistics::statisticsLogic($data['id'],$data['audit_result']);
        UnqualifiedCase::create($un_data);
        if(!empty($img)){
            HistoryImg::create($img);
        }
        $model->save($data);
        return $this->response();

    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/27
     * @Time: 17:43
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除案件
     */
    public function delCase($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $case = ModelCase::find($id);
            if (is_null($case)) {
                return $this->response(404, '此案件不存在');
            }
            //->force()
            $case->delete();
        }
        return $this->response();
    }

    /**
     * @param $file
     * @User: 刘海龙
     * @Date: 2021/7/28
     * @Time: 9:12
     * @return \think\response\Json
     * 上传案件
     */
    public function updateImgUrl()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->save($file, 'review_case_img');
        return $this->response($result);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/28
     * @Time: 9:51
     * @return \think\response\Json
     * @throws \Exception
     * 新增案件
     */
    public function saveReviewCase()
    {
        $data = $this->request->param();
        //判断样本点是否为新增样本
        $sample = ModelSample::find($data['new_sample_id']);
        if (is_null($sample)){
            //新增样本点
            $sample_id = ModelSample::create([
                'name'=>$data['new_sample_id'] ?? '',
                'review_project_id'=>$data['review_project_id'] ?? 0
            ])->id;
            $community_id = $data['community_id']; //社区
            $project_target_id = $data['project_target_id']; //项目指标
            $sample = ModelSample::find($sample_id);
            SampleCommunityPivot::sampleCommunitySave($sample,$community_id);
            SampleProjectTargetPivot::sampleProjectTargetSave($sample,$project_target_id);

        }else{
            $sample_id = $data['new_sample_id'] ?? 0;
        }
        $new_arr = [];
        if (sizeof($data['img_path']) > 0) {
            foreach ($data['img_path'] as $key => $value) {
                $new_arr[$key]['sync_path'] = json_encode($value['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?? '';
                $new_arr[$key]['domain'] = $value['domain'];
                $new_arr[$key]['remark'] = $data['remark'];
                $new_arr[$key]['review_project_id'] = $data['review_project_id'];
                $new_arr[$key]['new_sample_id'] = $sample_id;
            }
        }
        $case = new ModelCase();
        $case->saveAll($new_arr);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/28
     * @Time: 10:54
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 编辑案件
     */
    public function saveEditReviewCase()
    {
        $data = $this->request->param();
        $case = ModelCase::find($data['id']);
        if (is_null($case)) {
            return $this->response(403, '无法找到该案件');
        }
        if (array_key_exists('img_path', $data)) {
            foreach ($data['img_path'] as $key => $value) {
                $data['sync_path'] = json_encode($value['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?? '';
            }
        }
        $case->save($data);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 17:31
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 初始化列表
     */
    public function getReviewCaseWxList()
    {
        $map = [];
        $review_project = ReviewProject::where(['is_start' => 1])->find();
        if (is_null($review_project)) {
            return $this->response(403, '暂无项目');
        }
        $user = \app\model\User::find($this->request->wx_user_id); //通过人找到所属社区
        if (is_null($user)) {
            return $this->response(403, '查无此人');
        }
        //社区id
        $community = new ModelCommunity();
        $ids = $community->selectSample($user->community_id, $review_project->id);
        $map[] = ['new_sample_id', 'in', $ids];
        $map[] = ['review_status', '=', $this->request->param('review_status', ModelCase::ONE_REVIEW_STATUS)];
        //审核状态
        if ($this->request->has('audit_status') && !empty($this->request->param('audit_status'))) {
            $map[] = ['audit_status', '=', $this->request->param('audit_status')];
        }
        //审核结果
        if ($this->request->has('audit_result') && !empty($this->request->param('audit_result'))) {
            $audit_result_arr = explode(',', $this->request->param('audit_result'));
            $map[] = ['audit_result', 'in', $audit_result_arr];
        }
        if ($this->request->has('type') && !empty($this->request->param('type'))) {
            if ($this->request->param('type') !== 'cg'){ //不等于常规复查 复查工作台 新增当前自己的案件
                $map[] = ['review_people', '=', $this->request->wx_user_id];
            }
        }
        $limit = $this->request->param('limit', 10);
        $res = ModelCase::with(['project', 'unqualified.unadmin', 'sample' => ['communities', 'targets'], 'admin'])->where($map)->order('id desc')->paginate($limit)->each(function ($item, $key) {
            $item['url'] = $item['domain'] . json_decode($item['sync_path'], true);
            if ($item['review_status'] === ModelCase::TWO_REVIEW_STATUS) {
                $review_img = (json_decode($item['review_case_path'], true));
                $item['review_img'] = $review_img;
            }
            if ($item['audit_result'] === ModelCase::TOUR_AUDIT_RESULT) {
                $item['unqualified'] = $item['unqualified']->toArray();
            }
            return $item;
        });
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 15:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 复查案件提交
     */
    public function saveWxReviewCase()
    {
        $data = $this->request->param();
        $audit_result =  $data['audit_result'] ?? '';
        $audit_status =  $data['audit_status'] ?? '';
        $review_status =  $data['review_status'] ?? '';
        $data['review_case_path'] = json_encode($data['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $data['review_status'] = ModelCase::TWO_REVIEW_STATUS;//复查状态
        $case = ModelCase::find($data['id']);
        if (is_null($case)) {
            return $this->response(403, '暂未找到该案件');
        }
        if ($data['type'] === 'un') { //不合格案件
//            $data['audit_result'] = ModelCase::ZERO_AUDIT_RESULT;//重置审核结果
            $data['audit_status'] = ModelCase::ONE_AUDIT_STATUS;//重置审核状态
//            $data['audit_people'] = 0;//重置审核状态
            //更新不合格案件状态
            UnqualifiedCase::where(['review_case_id' => $data['id']])->update([
                'un_status' => UnqualifiedCase::UNQALIFIED_TWO
            ]);
        }else{
            $data['audit_status'] = ModelCase::ONE_AUDIT_STATUS;//重置审核状态
        }
        $data['review_time'] = date("Y-m-d H:i:s",time()) ?? time();
        unset($data['audit_result']);
        $case->save($data);
        //推送
        $this->bind($data['review_people'], $review_status, $audit_status, $audit_result);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/30
     * @Time: 18:00
     * @return \think\response\Json
     * 发送短信
     */
    public function getSmsCode()
    {
        $EXPIRE_SEC = 900;    // 过期时间间隔
        $mobile = $this->request->param('mobile', '');
        if (!isMobile($mobile)) {
            return $this->response(403, '这个手机号很奇葩哦，请正确输入后重试');
        }
        // 获取验证码
        $code = generate_code(4); //验证码
        $vcKey = 'VC_' . $mobile;
        $is_key = $this->redis->EXISTS($vcKey);
        if ($is_key === 0) {
            $res = $this->sendSms($mobile, $code);
            if ($res['result'] === 0) {
                $data = array('vc' => $code);
                $this->redis->set($vcKey, json_encode($data));
                $this->redis->expire($vcKey, $EXPIRE_SEC); // 设置验证码过期时间
            }
        } else {
            // 验证码重发限制
            $data = json_decode($this->redis->get($vcKey), true);
            $vc = $data['vc'];
            $res = $this->sendSms($mobile, $vc);
            if ($res['result'] === 0) {
                $ttl = $this->redis->ttl($vcKey);
                $this->redis->set($vcKey, json_encode($data));
                $this->redis->expire($vcKey, $ttl + $EXPIRE_SEC);
            }
        }
        return $this->response();
    }

    /**
     * @param $mobile
     * @param $vc
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 16:33
     * @return mixed
     * 发送短信
     */
    public function sendSms($mobile, $vc)
    {
        $phoneNumbers = [$mobile];
        $AppId = Config::get('sms.AppId');
        $key = Config::get('sms.AppKey');
        $templateId = Config::get('sms.template');
        $smsSign = Config::get('sms.sign');
        $msender = new SmsMultiSender($AppId, $key);
        $params = [$vc, '15'];
        $result = $msender->sendWithParam("86", $phoneNumbers,
            $templateId, $params, $smsSign, "", "");  // 签名参数不能为空串
        $rsp = json_decode($result, true);

        return $rsp;
    }

    /**
     * @param $review_people //复查人
     * @param $review_status //复查状态
     * @param $audit_status //审核状态
     * @param $audit_result //审核结果
     * @param $client_id //客户端id
     * @User: 刘海龙
     * @Date: 2021/8/4
     * @Time: 10:12
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 常规未复查案件消息推送
     */
    public function bind($review_people, $review_status, $audit_status, $audit_result)
    {
//        halt($review_people, $review_status, $audit_status, $audit_result);
        $review_project = ReviewProject::where(['is_start' => 1])->find();
        $community = new ModelCommunity();
        $user = \app\model\User::find($review_people); //通过人找到所属社区
        if (is_null($user)) {
            return $this->response(403, '查无此人');
        }
        //audit_result
        //通过社区id和当前所属项目找到对应的样本点
        $ids = $community->selectSample($user->community_id, $review_project->id);
        $map[] = ['new_sample_id', 'in', $ids];
        $map[] = ['review_status', '=', $review_status];

        if (!empty($audit_status)){
            $map[] = ['audit_status', '=', $audit_status];
        }
        if (!empty($audit_result)){
            $map[] = ['audit_result', 'in', explode(',',$audit_result)];
        }

        $res = ModelCase::with(['project', 'sample' => ['communities', 'targets'], 'admin'])->where($map)->order('id desc')->select()->toArray();
        foreach ($res as $key => $item) {
            $res[$key]['url'] = $item['domain'] . json_decode($item['sync_path'], true);
        }
        $total = count($res);
        //不转义中文不加反斜杠
        $res = json_encode(array('type' => 'dataSource', 'code' => 200, 'list' => $res, 'totalCount' => $total), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        //当前任务将由哪个类来负责处理
        $jobHandlerClassName = 'app\job\SyncOnePlaceToES';
        //队列名称
        $jobQueueName = "createOrderJob";
        $data = [
            'res' => $res
        ];
        //入队列，later延时发送，单位秒。push立即发送
        Queue::push($jobHandlerClassName, $data, $jobQueueName);
    }


    //不合格案件推送
    public function bindUnqualifiedCase()
    {
        //当前任务将由哪个类来负责处理
        $jobHandlerClassName = 'app\job\SyncUnqualifiedCase';
        //队列名称
        $jobQueueName = " unqualifiedCaseJob";
        $data = [
            'res' => json_encode(array('type' => 'dataSource', 'code' => 200, 'list' => ['id' => 333], 'totalCount' => 22), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
        ];
        //入队列，later延时发送，单位秒。push立即发送
        Queue::push($jobHandlerClassName, $data, $jobQueueName);
    }
}
